package com.my.ads.lib.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.cleantest.MemoryBoosterActivity;
import com.my.ads.lib.AdSummary;
import com.my.ads.lib.Config;
import com.rapid.clean.deep.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * Created by xuanyang on 2018/3/15.
 */

public class LockScreenNoticeActivity extends FragmentActivity {

    private ImageView img_lock_gift, img_menu;
    private TextView my_time, my_date, my_week;
    private TextView bottom_action;
    private RelativeLayout relative_ad_5, relative_ad_6;
    private RelativeLayout relative_ad_lock;
    private TextView text_notice;

    private PopupWindow pw;
    private LayoutInflater inflater;

    private TimeReceiver myBroadcastReceiver;
    private IntentFilter intentFilter;

    int x1, x2;
    private boolean isOpen = false;
    private boolean flag = false;
    private boolean ad_flag = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        setContentView(R.layout.lock_screen_2);

        initViews();


        initReceiver();
        click();
        getVersionName();


    }

    private void initReceiver() {
        //注册广播
        myBroadcastReceiver = new TimeReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(Intent.ACTION_DATE_CHANGED);
        registerReceiver(myBroadcastReceiver, intentFilter);
    }

    private void click() {
        img_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.menu_layout, null);
                TextView textView = (TextView) view.findViewById(R.id.text_off);
                pw = new PopupWindow(view, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                pw.setFocusable(true);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
                pw.showAsDropDown(img_menu);
            }
        });

        img_lock_gift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                Intent intent = new Intent(LockScreenNoticeActivity.this, GiftActivity.class);
                startActivity(intent);
            }
        });

        bottom_action.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    x1 = (int) event.getX();
                }
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    x2 = (int) event.getX();
                    if ((x2 - x1) > 100) {
                        if (!isOpen) {
                            virbate();
                            finish();

                            Random random1 = new Random();
                            Log.e("sad", Integer.valueOf(Config.boost_rate) + "ss");
                            if ((random1.nextInt(100) + 1) <= Integer.valueOf(Config.boost_rate)) {
                                finish();
                                Intent intent1 = new Intent(LockScreenNoticeActivity.this, MemoryBoosterActivity.class);
                                startActivity(intent1);
                            }
                            isOpen = true;
                        }


                    }
                }
                return true;
            }
        });

        text_notice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!flag) {
                    flag = true;
                    relative_ad_lock.setVisibility(View.VISIBLE);
                    AdSummary.getInstance().showNativeAd(LockScreenNoticeActivity.this, relative_ad_lock, true);

                } else {
                    flag = false;
                    relative_ad_lock.setVisibility(View.GONE);
                }

//                if (FacebookNative.mAdsCache_new.size() > 0 || FacebookNative.mAdsCache.size() > 0
//                        || AdxNative.getInstance().new_list_adx_nativeAd.size() > 0 || AdxNative.getInstance().list_adx_nativeAd.size() > 0
//                        || AdmobNative.getInstance().new_list_adx_nativeAd.size() > 0 || AdmobNative.getInstance().list_adx_nativeAd.size() > 0) {
//                    text_notice.setVisibility(View.VISIBLE);
//                } else {
//                    text_notice.setVisibility(View.GONE);
//                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();

        my_time.setText(getSystemTime());
        my_date.setText(getSystemDate());
        my_week.setText(getSystemWeek(1));

        if (ad_flag) {
            SharedPreferences sp_1 = getSharedPreferences("native_ad", Context.MODE_PRIVATE);
            Long show_time = sp_1.getLong("show_native_ad_time", 0L);
            if (show_time != 0L && ((System.currentTimeMillis() - show_time) > Integer.valueOf(Config.update_native_ad) * 1000)) {
                try {
                    AdSummary.getInstance().showNativeAd(LockScreenNoticeActivity.this, relative_ad_5, false);
                } catch (Exception e) {
                }
            }

            SharedPreferences sp_3 = getSharedPreferences("banner_ad", Context.MODE_PRIVATE);
            Long show_time_ad_3 = sp_3.getLong("show_banner_ad_time", 0L);

            if (show_time_ad_3 != 0L && (System.currentTimeMillis() - show_time_ad_3 >= (Integer.valueOf(Config.update_native_ad) * 1000))) {
                AdSummary.getInstance().showBannerAd(relative_ad_6);
            }

//            if (AdxNative.getInstance().new_list_adx_nativeAd.size() > 0 || AdxNative.getInstance().list_adx_nativeAd.size() > 0
//                    || AdmobNative.getInstance().new_list_adx_nativeAd.size() > 0 || AdmobNative.getInstance().list_adx_nativeAd.size() > 0) {
//                text_notice.setVisibility(View.VISIBLE);
//            } else {
//                text_notice.setVisibility(View.GONE);
//            }
        }
    }


    private void initViews() {
        img_menu = (ImageView) findViewById(R.id.img_menu);
        my_time = (TextView) findViewById(R.id.tv_time);
        my_date = (TextView) findViewById(R.id.tv_year_time);
        my_week = (TextView) findViewById(R.id.week);
        bottom_action = (TextView) findViewById(R.id.bottom_action);
        img_lock_gift = (ImageView) findViewById(R.id.img_lock_gift);
        relative_ad_5 = (RelativeLayout) findViewById(R.id.relative_ad_5);
        relative_ad_6 = (RelativeLayout) findViewById(R.id.relative_ad_6);
        relative_ad_lock = (RelativeLayout) findViewById(R.id.relative_ad_lock);
        text_notice = (TextView) findViewById(R.id.text_notice);
    }

    private String getSystemTime() {
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        return t1;
    }

    private String getSystemDate() {
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        return t1;
    }

    private String getSystemWeek(int temp) {
        Log.e("dsa", "aa" + temp);
        Calendar c = Calendar.getInstance();
        String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(mWay)) {
            mWay = "Sunday";
        } else if ("2".equals(mWay)) {
            mWay = "Monday";
        } else if ("3".equals(mWay)) {
            mWay = "Tuesday";
        } else if ("4".equals(mWay)) {
            mWay = "Wednesday";
        } else if ("5".equals(mWay)) {
            mWay = "Thursday";
        } else if ("6".equals(mWay)) {
            mWay = "Friday";
        } else if ("7".equals(mWay)) {
            mWay = "Saturday";
        }
        return mWay;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myBroadcastReceiver != null) {
            unregisterReceiver(myBroadcastReceiver);
        }
    }

    /**
     * virbate means that the screen is unlocked success
     */
    private void virbate() {
        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    class TimeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("dsa", "11");
            try {
                if (Intent.ACTION_TIME_TICK.equals(intent.getAction())) {
                    my_time.setText(getSystemTime());
                } else if (Intent.ACTION_DATE_CHANGED.equals(intent.getAction())) {
                    my_date.setText(getSystemDate());
                    my_week.setText(getSystemWeek(2));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void getVersionName() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                StringBuilder response = null;
                try {
                    Log.v("lock_url", "url: " + "https://play.google.com/store/apps/details?id=" + getPackageName());
                    //创建URL对象，并传入目标的网络地址
                    URL url = new URL("https://play.google.com/store/apps/details?id=" + getPackageName());
                    //调用一下 openConnection()方法获得HttpURLConnection实例
                    connection = (HttpURLConnection) url.openConnection();
                    //设置一下 HTTP请求所使用的方法,get表示希望从服务器那里获取数据
                    connection.setRequestMethod("GET");
                    //设置连接超时
                    connection.setConnectTimeout(5000);
                    //设置读取超时
                    connection.setReadTimeout(5000);
                    //设置utf-8
                    connection.setRequestProperty("Charset", "utf-8");
                    //调用 getInputStream()方法就可以获取到服务器返回的输入流
                    InputStream input = connection.getInputStream();
                    //接下来就是读取输入流
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    String msg = response.substring(response.indexOf("softwareVersion") + 17).substring(0, response.substring(response.indexOf("softwareVersion") + 17).indexOf("</div>"));

                    Log.v("lock_url", "msg: " + msg);

                    if (!msg.trim().equals(getVerName(LockScreenNoticeActivity.this))) {
                        ad_flag = true;
                        try {
                            AdSummary.getInstance().showNativeAd(LockScreenNoticeActivity.this, relative_ad_5, true);
                            AdSummary.getInstance().showBannerAd(relative_ad_6);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

//                        if (AdxNative.getInstance().new_list_adx_nativeAd.size() > 0 || AdxNative.getInstance().list_adx_nativeAd.size() > 0
//                                || AdmobNative.getInstance().new_list_adx_nativeAd.size() > 0 || AdmobNative.getInstance().list_adx_nativeAd.size() > 0) {
//                            text_notice.setVisibility(View.VISIBLE);
//                        } else {
//                            text_notice.setVisibility(View.GONE);
//                        }

                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        //关闭HTTP连接
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }


    private String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("msg", e.getMessage());
        }
        return verName;
    }
}
